package com.example.taobaounion3.presenter.impl;

import com.example.taobaounion3.model.Api;
import com.example.taobaounion3.model.domain.Categories;
import com.example.taobaounion3.presenter.IHomePresenter;
import com.example.taobaounion3.utils.LogUtils;
import com.example.taobaounion3.utils.RetrofitManager;
import com.example.taobaounion3.view.IHomeCallback;

import java.net.HttpURLConnection;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class HomePresenterlmpl implements IHomePresenter {

    private IHomeCallback mCallback=null;

    @Override
    public void getCategories() {
        if (mCallback!=null){
            mCallback.onLoading();
        }
        //加载分类数据
        Retrofit retrofit= RetrofitManager.getOurInstance().getRetrofit();
        Api api=retrofit.create(Api.class);
        Call<Categories> task=api.getCategories();
        task.enqueue(new Callback<Categories>() {
            @Override
            public void onResponse(Call<Categories> call, Response<Categories> response) {
                //数据结果
                int code=response.code();
                LogUtils.d(HomePresenterlmpl.this,"result code is -->"+code);
                if(code== HttpURLConnection.HTTP_OK){
                    //请求成功
                    Categories categories=response.body();
//                    LogUtils.d(HomePresenterlmpl.this,categories.toString());
                    if (mCallback!=null){
                        if (categories==null||categories.getData().size()==0){
                            mCallback.onEmpty();
                        }else {
                            mCallback.onCategoriesLoaded(categories);
                        }

                    }
                }else {
                    //请求失败
                    LogUtils.i(HomePresenterlmpl.this,"请求失败");
                    if (mCallback!=null){
                        mCallback.onError();
                    }
                }
            }

            @Override
            public void onFailure(Call<Categories> call, Throwable t) {
                //加载失败的结果
                LogUtils.e(this,"请求错误..."+t);
                if (mCallback!=null){
                    mCallback.onError();
                }
            }
        });

    }

    @Override
    public void registerViewCallback(IHomeCallback callback) {
        this.mCallback=callback;

    }

    @Override
    public void unregisterViewCallback(IHomeCallback callback) {
        mCallback=null;
    }
}
